import { Extra } from "@/api/interface/Search/Extra";
import { ReqSearch } from "@/api/interface/Search/ReqSearch";
import { Field } from "@/api/interface/Search/Field";
import { ColumnProps } from "@/components/ProTable/interface";
import { KeyInputBetweenMax, KeyInputBetweenMin } from "@/tsx/searchRender";

//构造向后端请求的search 列表参数
export const BuildSearchWhere = (params: any, listCols: ColumnProps[]): ReqSearch => {
  let extra: Extra = {
    pageNum: params.pageNum,
    pageSize: params.pageSize
  };

  //构造搜索参数
  let whereOpts: Array<Field> = [];
  for (const paramsKey in params) {
    if (paramsKey == "pageNum" || paramsKey == "pageSize") continue;
    //获取列的信息
    let props = GetListColumnPropInfo(paramsKey, listCols);

    //获取该字段的搜索条件=
    let optWhere = props.search?.optWhere ?? "="; //默认是=
    let optValue: any = params[paramsKey];

    //like
    if (optWhere == "LIKE") {
      optValue = "%" + optValue + "%";
    }
    //BETWEEN
    if (optWhere == "BETWEEN") {
      if (!Array.isArray(optValue)) continue; //如果是非数组则丢弃
      if (optValue.length < 1) continue; //数组值数量必须大于1个,否则丢弃
      optValue = optValue.filter(s => s != ""); //删除空字符
      if (optValue.length == 1) {
        optValue = [optValue[0], optValue[0]];
      }
      //只输入了一个 则将初始值和结束值都设置成一个
    }

    //向where列表新增参数
    whereOpts.push({ field: paramsKey, opt: optWhere, value: optValue });
  }

  //校验一下参数
  let resultWhereOpts = whereOpts.filter(item => {
    if (item.opt == "BETWEEN" && item.value.length <= 0) {
      return false; //BETWEEN数量不能为0个
    }
    return true;
  });

  //构造向后端请求的数据结果
  let res = {
    extra: extra,
    wheres: resultWhereOpts
  };
  console.log(res, "res -- console.log");
  return res;
};

//获取列表一列的信息
export const GetListColumnPropInfo = (filedName: string, listCols: ColumnProps[]): ColumnProps => {
  let data = listCols.filter((s: ColumnProps) => {
    return s.prop == filedName;
  });

  if (data.length > 0) {
    return data[0];
  }

  return {};
};
